<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务，帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace app\store\model;

use app\api\model\wxapp\Setting as WxappSettingModel;
use app\common\library\wechat\WxSendGood;
use app\store\model\Supplier as SupplierModel;
use app\common\model\Order as OrderModel;
use app\common\model\OrderSub as OrderSubModel;
use app\common\service\Order as OrderService;
use app\common\service\Message as MessageService;
use app\common\service\order\Refund as RefundService;
use app\common\enum\order\OrderStatus as OrderStatusEnum;
use app\common\enum\order\PayStatus as PayStatusEnum;
use app\common\enum\order\DeliveryType as DeliveryTypeEnum;
use app\common\enum\order\ReceiptStatus as ReceiptStatusEnum;
use app\common\enum\order\DeliveryStatus as DeliveryStatusEnum;
use app\common\library\helper;
use app\store\service\store\User as StoreUserService;

/**
 * 订单管理
 * Class Order
 * @package app\store\model
 */
class Order extends OrderModel
{
    // 全部订单
    const LIST_TYPE_ALL = 'all';

    // 待发货订单
    const LIST_TYPE_DELIVERY = 'delivery';

    // 待收货订单
    const LIST_TYPE_RECEIPT = 'receipt';

    // 待付款订单
    const LIST_TYPE_PAY = 'pay';

    // 已完成订单
    const LIST_TYPE_COMPLETE = 'complete';

    // 已取消
    const LIST_TYPE_CANCEL = 'cancel';

    /**
     * 订单详情页数据
     * @param int $orderId
     * @return Order|array|false|null
     */
    public function getDetail(int $orderId)
    {
        return static::detail($orderId, [
            'user',
            'address',
            'goods' => ['image', 'refund'],
            'express',
        ]) ?: false;
    }

    /**
     * 父类订单数据详情
     * @param int $orderParentId
     * @return Order|array|false|null
     */
    public function getParentDetail(int $orderParentId)
    {
        return static::detail($orderParentId, [
            'address',
            'order_sub'
        ]) ?: false;
    }

    /**
     * 订单列表
     * @param string $dataType 订单类型
     * @param array $param
     * @return mixed
     */
    public function getList(string $dataType = self::LIST_TYPE_ALL, array $param = [])
    {
        // 检索查询条件
        $filter = $this->getQueryFilter($param);
        if (isset($param['payType']) && $param['payType'] == 10) {//余额支付
            $filter[] = ['order_sub.bd_type', '=', '10'];
            $filter[] = ['order_sub.deduction_value', '>', '0.00'];
            $filter[] = ['order_sub.pay_original_money', '=', '0.00'];
        } elseif (isset($param['payType']) && $param['payType'] == 20) {//微信支付
            $filter[] = ['order_sub.deduction_value', '=', '0.00'];
            $filter[] = ['order_sub.pay_original_money', '>', '0.00'];
        } elseif (isset($param['payType']) && $param['payType'] == 30) {//邦豆支付
            $filter[] = ['order_sub.bd_type', '=', '7'];
            $filter[] = ['order_sub.deduction_value', '>', '0.00'];
            $filter[] = ['order_sub.pay_original_money', '=', '0.00'];
        } elseif (isset($param['payType']) && $param['payType'] == 40) {//微信+邦豆支付
            $filter[] = ['order_sub.bd_type', '=', '7'];
            $filter[] = ['order_sub.deduction_value', '>', '0.00'];
            $filter[] = ['order_sub.pay_original_money', '>', '0.00'];
        } elseif (isset($param['payType']) && $param['payType'] == 50) {//微信加现金券支付
            $filter[] = ['order_sub.bd_type', '=', '6'];
        } elseif (isset($param['payType']) && $param['payType'] == 60) {//微信加礼金券支付
            $filter[] = ['order_sub.bd_type', '=', '5'];
        } elseif (isset($param['payType']) && $param['payType'] == 70) {//微信加余额支付
            $filter[] = ['order_sub.bd_type', '=', '10'];
            $filter[] = ['order_sub.deduction_value', '>', '0.00'];
            $filter[] = ['order_sub.pay_original_money', '>', '0.00'];
        }

        // 设置订单类型条件
        $dataTypeFilter = $this->getFilterDataType($dataType);
        $orderList = $this->with(['goods.image', 'user.avatar'])
            ->alias('order')
            ->field('order.*,order_sub.pay_type,order_sub.bd_type,order_sub.deduction_value,order_sub.pay_money,order_sub.pay_original_money')
            ->leftJoin('user', 'user.user_id = order.user_id')
            ->leftJoin('order_address address', 'address.order_id = order.order_id')
            ->leftJoin('order_sub', 'order_sub.order_id = order.order_id or order_sub.order_id = order.order_parent_id')
            ->where($dataTypeFilter)
            ->where($filter)
            ->where('order.is_delete', '=', 0)
            ->where(function ($query) use ($dataType) {
                if ($dataType == self::LIST_TYPE_ALL) {//全部订单
                    $orwhere = [['order.order_parent_id', '>', '0'], ['order.pay_status', '=', '10']];
                    $query->whereOr($orwhere);
                } elseif ($dataType == self::LIST_TYPE_PAY) {
                    $query->where('order.order_parent_id', '=', 0);
                }else {
                    $query->where('order.order_parent_id', '>', 0);
                }

            })
            ->order(['order.order_id' => 'desc'])
            ->paginate(10)->toArray();
        if (isset($orderList['data']) && $orderList['data']) {
            $supplierModel = new SupplierModel;
            $supplierList  = $supplierModel->getListByCategory()->toArray();//所有供应商
            $supplierList  = array_column($supplierList, 'business_name', 'supplier_id');
            //数据处理
            foreach ($orderList['data'] as $key => $value) {
                foreach ($value['goods'] as $item) {
                    if ($item['good_type'] == 'virtual_good') {//虚拟商品
                        $orderList['data'][$key]['recharge_account'] = $item['recharge_account'];
                        $orderList['data'][$key]['delivery_type']    = 20;
                    }
                }
                $orderList['data'][$key]['good_type']     = $value['goods'][0]['good_type'];
                $orderList['data'][$key]['supplier_name']= $supplierList[$value['supplier_id']] ?? '自营';
                $orderList['data'][$key]['pay_type'] = $this->payMethod($value['pay_original_money'], $value['bd_type'], $value['deduction_value']);
            }
        }
        return $orderList;
    }

    /**
     * 支付方式
     * @param $pay_money
     * @param $bd_type
     * @return string
     */
    public function payMethod($pay_money, $bd_type, $deduction_value)
    {
        if ($pay_money == '0.00' && $bd_type == 10) {//余额支付
            return 10;
        }
        if ($bd_type == 0) {//现金支付
            return 20;
        }
        if ($pay_money == '0.00' && $bd_type == 7) {//帮豆支付
            return 30;
        }
        if ((float)$deduction_value > 0 && $bd_type == 7 && (float)$pay_money > 0) {//微信+邦豆
            return 40;
        }
        if ($bd_type == 6 && $pay_money > 0) {//微信+现金券
            return 50;
        }
        if ($bd_type == 5 && $pay_money > 0) {//微信+礼金券
            return 60;
        }
        if ($deduction_value > 0 && $bd_type == 10 && $pay_money > 0) {//微信+余额
            return 70;
        }
        return 20;
    }

    /**
     * 订单分单后支付方式
     * @param $goods
     * @return string
     */
    public function payMoney($goods)
    {
        $pay_money       = 0.00;
        $deduction_value = 0.00;
        $typeName        = '';
        $payMethod       = '';
        $bd_type         = 0;
        if ($goods) {
            foreach ($goods as $value) {
                $bd_type = $value['bd_type'];
                if ($value['bd_type'] == 7) {
                    $typeName = ' 邦豆';
                } elseif ($value['bd_type'] == 6) {
                    $typeName = ' 现金券';
                } elseif ($value['bd_type'] == 5) {
                    $typeName = ' 礼金券';
                } elseif ($bd_type == 10) {
                    $typeName = ' 余额';
                }
                if ($value['pay_cash'] > 0) {
                    $payMethod = '微信';
                }
                $pay_money       = helper::bcadd($pay_money, $value['pay_cash']);
                $deduction_value = helper::bcadd($deduction_value, $value['deduction_value']);
            }
        }
        $symbol = '';
        if ($payMethod && $bd_type) {
            $symbol = ' + ';
        }
        $cash = '';
        if ($pay_money > 0) {
            $cash = $payMethod . $pay_money . "元";
        }
        $bangdou = '';
        if ($deduction_value > 0) {
            $bangdou = $deduction_value . $typeName;
        }
        return $cash . $symbol . $bangdou;
    }

    /**
     * 订单分单前支付方式
     * @param $goods
     * @return string
     */
    public function payMoneyOld($pay_money, $bd_type, $deduction_value)
    {
        $typeName = '';
        if ($bd_type == 7) {
            $typeName = ' 邦豆';
        } elseif ($bd_type == 6) {
            $typeName = ' 现金券';
        } elseif ($bd_type == 5) {
            $typeName = ' 礼金券';
        } elseif ($bd_type == 10) {
            $typeName = ' 余额';
        }
        $deduction_value = $deduction_value > 0 ? $deduction_value : '';
        $payMethod       = '';
        if ($pay_money > 0) {
            $payMethod = '微信';
        }
        $symbol = '';
        if ($payMethod && $bd_type) {
            $symbol = ' + ';
        }
        $pay_money = $pay_money > 0 ? $pay_money : '';
        return $payMethod . $pay_money . $symbol . $deduction_value . $typeName;
    }

    /**
     * 订单列表(全部)
     * @param string $dataType 订单类型
     * @param array $query
     * @return mixed
     */
    public function getListAll(string $dataType = self::LIST_TYPE_ALL, array $query = [])
    {
        // 检索查询条件
        $queryFilter = $this->getQueryFilter($query);
        // 设置订单类型条件
        $dataTypeFilter = $this->getFilterDataType($dataType);
        // 获取数据列表
        return $this->with(['goods.image', 'address', 'user.avatar', 'express'])
            ->alias('order')
            ->field('order.*')
            ->join('user', 'user.user_id = order.user_id')
            ->where($dataTypeFilter)
            ->where($queryFilter)
            ->where('order.is_delete', '=', 0)
            ->order(['order.create_time' => 'desc'])
            ->select();
    }

    /**
     * 设置检索查询条件
     * @param array $param
     * @return array
     */
    private function getQueryFilter(array $param): array
    {
        // 默认参数
        $params = $this->setQueryDefaultValue($param, [
            'searchType'   => '',     // 关键词类型 (10订单号 20会员昵称 30会员ID 40收货人姓名 50收货人电话)
            'searchValue'  => '',    // 关键词内容
            'orderSource'  => -1,    // 订单来源
            'deliveryType' => -1,   // 配送方式
            'betweenTime'  => [],    // 起止时间
            'userId'       => 0,          // 会员ID
            'supplierIds'  => [],     // 供应商Id
        ]);
        // 检索查询条件
        $filter = [];
        // 关键词
        if (!empty($params['searchValue'])) {
            $searchWhere = [
                10 => ['order.order_no', 'like', "%{$params['searchValue']}%"],
                20 => ['user.nick_name', 'like', "%{$params['searchValue']}%"],
                30 => ['order.user_id', '=', (int)$params['searchValue']],
                40 => ['address.name', 'like', "%{$params['searchValue']}%"],
                50 => ['address.phone', 'like', "%{$params['searchValue']}%"],
            ];
            array_key_exists($params['searchType'], $searchWhere) && $filter[] = $searchWhere[$params['searchType']];
        }
        // 起止时间
        if (!empty($params['betweenTime'])) {
            $times    = between_time($params['betweenTime']);
            $filter[] = ['order.create_time', '>=', $times['start_time']];
            $filter[] = ['order.create_time', '<', $times['end_time'] + 86400];
        }
        // 供应商id
        if ($params['supplierIds']) {
            $filter[] = ['order.supplier_id', 'in', $params['supplierIds']];
            //$filter[] = ['order.order_status', '<>', OrderStatusEnum::CANCELLED];
        }
        // 订单来源
        $params['orderSource'] > -1 && $filter[] = ['order_source', '=', (int)$params['orderSource']];
        // 配送方式
        $params['deliveryType'] > -1 && $filter[] = ['delivery_type', '=', (int)$params['deliveryType']];
        // 用户id
        $params['userId'] > 0 && $filter[] = ['order.user_id', '=', (int)$params['userId']];
        return $filter;
    }

    /**
     * 设置订单类型条件
     * @param string $dataType
     * @return array
     */
    private function getFilterDataType(string $dataType = self::LIST_TYPE_ALL): array
    {
        // 数据类型
        $filter = [];
        switch ($dataType) {
            case self::LIST_TYPE_ALL:
                $filter = [];
                break;
            case self::LIST_TYPE_DELIVERY:
                $filter = [
                    ['pay_status', '=', PayStatusEnum::SUCCESS],
                    ['delivery_status', '=', DeliveryStatusEnum::NOT_DELIVERED],
                    ['order_status', 'in', [OrderStatusEnum::NORMAL, OrderStatusEnum::APPLY_CANCEL]]
                ];
                break;
            case self::LIST_TYPE_RECEIPT:
                $filter = [
                    ['pay_status', '=', PayStatusEnum::SUCCESS],
                    ['delivery_status', '=', DeliveryStatusEnum::DELIVERED],
                    ['receipt_status', '=', ReceiptStatusEnum::NOT_RECEIVED]
                ];
                break;
            case self::LIST_TYPE_PAY:
                $filter[] = ['pay_status', '=', PayStatusEnum::PENDING];
                $filter[] = ['order_status', '=', OrderStatusEnum::NORMAL];
                break;
            case self::LIST_TYPE_COMPLETE:
                $filter[] = ['order_status', '=', OrderStatusEnum::COMPLETED];
                break;
            case self::LIST_TYPE_CANCEL:
                $filter[] = ['order_status', '=', OrderStatusEnum::CANCELLED];
                break;
        }
        return $filter;
    }

    /**
     * 确认发货(单独订单)
     * @param $data
     * @return bool|false
     * @throws \Exception
     */
    public function delivery($data)
    {
        // 转义为订单列表
        $orderList = [$this];
        // 验证订单是否满足发货条件
        if (!$this->verifyDelivery($orderList)) {
            return false;
        }
        $this->transaction(function () use ($data) {
            // 获取已发货的订单
            $completed               = self::detail($this['order_id'], ['goods']);
            $completed['express_id'] = $data['express_id'];
            $completed['express_no'] = $data['express_no'];
            // 整理更新的数据
            $updateList = [[
                'order_id'       => $this['order_id'],
                'express_id'     => $data['express_id'],
                'express_no'     => $data['express_no'],
                'express_remark' => $data['express_remark'] ?? '',
            ]];
            if ($data['express_id'] == 10002 && $data['express_no'] == '8197708048603') {//用户自提，手动去微信小程序发货
                $updateList[0]['express_id'] = '';
                $updateList[0]['express_no'] = '用户自提';
                $deliveryMethod = 4;//4用户自提
            } else {
                $deliveryMethod = 1;//1物流配送
            }
            //查询子订单是否有发货同步到微信的
            $isSyncWx = $this->where('order_parent_id', '=', $this['order_parent_id'])
                ->where('delivery_status', '=', 20)
                ->find();
            // 更新订单发货状态
            $this->updateToDelivery($updateList);
            $ordersub = OrderSubModel::getOrderSubBy($this['order_parent_id']);//获去取支付信息*/
            //子订单没有发货 并且 微信支付金额不为0.00才去微信发货
            if (empty($isSyncWx) && $ordersub['pay_money'] != '0.00') {
                //发货同步到微信小程序
                $Wxapp      = WxappSettingModel::getWxappConfig($this['store_id']);
                $WxSendGood = new WxSendGood($Wxapp);
                $WxSendGood->syncMpWeixinShipping($completed, [
                    // 同步至微信小程序《发货信息录入》
                    'syncMpWeixinShipping' => 1,
                    // 物流模式：1物流配送 3虚拟商品 4用户自提
                    'logisticsType'        => $deliveryMethod,
                    // 物流公司ID
                    'expressId'            => $updateList[0]['express_id'],
                    // 物流单号
                    'expressNo'            => $updateList[0]['express_no'],
                ]);
            }
            // 发送消息通知
            $this->sendDeliveryMessage([$completed]);
        });
        return $this['order_id'];
    }

    /**
     * 确认发货后发送消息通知
     * @param $orderList
     * @return bool
     */
    private function sendDeliveryMessage($orderList): bool
    {
        // 微信消息订阅通知
        foreach ($orderList as $item) {
            MessageService::WxMessageNotice('order.messagewx', ['order' => $item], self::$storeId);
        }
        /*// 发送消息通知
        foreach ($orderList as $item) {
            MessageService::send('order.delivery', ['order' => $item], self::$storeId);
        }*/
        return true;
    }

    /**
     * 更新订单发货状态(批量)
     * @param $orderList
     * @return bool
     */
    private function updateToDelivery($orderList): bool
    {
        // 整理更新的数据
        $data = [];
        foreach ($orderList as $item) {
            $data[] = [
                'data'  => [
                    'express_no'      => $item['express_no'],
                    'express_id'      => $item['express_id'],
                    'express_remark'  => $item['express_remark'],
                    'delivery_status' => 20,
                    'delivery_time'   => time(),
                    'admin_id' => StoreUserService::getLoginUserId(),
                ],
                'where' => ['order_id' => $item['order_id']]
            ];
        }
        // 批量更新
        $this->updateAll($data);
        return true;
    }

    /**
     * 验证订单是否满足发货条件
     * @param $orderList
     * @return bool
     */
    private function verifyDelivery($orderList): bool
    {
        foreach ($orderList as $order) {
            if (
                $order['pay_status'] != PayStatusEnum::SUCCESS
                || $order['delivery_type'] != DeliveryTypeEnum::EXPRESS
                || $order['delivery_status'] != DeliveryStatusEnum::NOT_DELIVERED
            ) {
                $this->error = "订单号[{$order['order_no']}] 不满足发货条件!";
                return false;
            }
        }
        return true;
    }

    /**
     * 修改订单价格
     * @param array $data
     * @return bool
     */
    public function updatePrice(array $data): bool
    {
        if ($this['pay_status'] != PayStatusEnum::PENDING) {
            $this->error = '该订单不合法';
            return false;
        }
        // 实际付款金额
        $payPrice = helper::bcadd($data['order_price'], $data['express_price']);
        if ($payPrice <= 0) {
            $this->error = '订单实付款价格不能为0.00元';
            return false;
        }
        // 改价的金额差价
        $updatePrice = helper::bcsub($data['order_price'], $this['order_price']);
        $orderNo     = $this->orderNo(); // 修改订单号, 否则微信支付提示重复
        $orderSub    = new OrderSubModel();
        //更新订单子表订单号
        $orderSub::update(['order_no' => $orderNo], ['order_id' => $this['order_id']]);
        // 更新订单记录
        return $this->save([
                'order_no'      => $orderNo, // 修改订单号, 否则微信支付提示重复
                'pay_price'     => $payPrice,
                'update_price'  => $updatePrice,
                'express_price' => $data['express_price'],
                'admin_id' => StoreUserService::getLoginUserId()
            ]) !== false;
    }

    /**
     * 审核：用户取消订单
     * @param array $data
     * @return bool|mixed
     */
    public function confirmCancel(array $data)
    {
        // 判断订单是否有效
        if (
            $this['pay_status'] != PayStatusEnum::SUCCESS
            || $this['order_status'] != OrderStatusEnum::APPLY_CANCEL
        ) {
            $this->error = '该订单不合法';
            return false;
        }
        // 订单取消事件
        return $this->transaction(function () use ($data) {
            $orderInfo = $this->toArray();
            if ($data['status']) {
                //获取订单下商品信息
                $result                        = static::detail($this['order_id'], ['goods']);
                $cancelData                    = $this;
                $cancelData['bd_type']         = 0;
                $cancelData['pay_cash']        = 0.00;
                $cancelData['deduction_value'] = 0.00;
                if ($result['goods']) {
                    foreach ($result['goods'] as $good_info) {
                        if ($good_info['bd_type'] != 0) {
                            $cancelData['bd_type'] = $good_info['bd_type'];
                        }
                        $cancelData['pay_cash']        = helper::bcadd($cancelData['pay_cash'], $good_info['pay_cash']);
                        $cancelData['deduction_value'] = helper::bcadd($cancelData['deduction_value'], $good_info['deduction_value']);
                    }
                }
                // 执行退款操作
                (new RefundService)->execute($cancelData);
                // 订单取消事件
                OrderService::cancelEvent($this);
                $orderInfo['refund_reason']   = '用户申请取消订单';
                $orderInfo['total_pay_price'] = $result['pay_price'];
                $param['remark']              = '退款成功';
            } else {
                $orderInfo['refund_reason']   = '用户申请取消订单';
                $orderInfo['total_pay_price'] = $orderInfo['pay_price'];
                $orderInfo['remark']          = '拒绝申请退款';
            }
            //微信消息订阅
            MessageService::WxMessageOrderRefund('order.messagewx', $orderInfo);
            // 更新订单状态
            return $this->save(['order_status' => $data['status'] ? OrderStatusEnum::CANCELLED : OrderStatusEnum::NORMAL,'admin_id' => StoreUserService::getLoginUserId()]);
        });
    }

    /**
     * 将订单记录设置为已删除
     * @return bool
     */
    public function setDelete(): bool
    {
        return $this->save(['is_delete' => 1,'admin_id' => StoreUserService::getLoginUserId()]) !== false;
    }

    /**
     * 获取已付款订单总数 (可指定某天)
     * @param null $startDate
     * @param null $endDate
     * @return int
     */
    public function getPayOrderTotal($startDate = null, $endDate = null): int
    {
        $filter = [
            ['pay_status', '=', PayStatusEnum::SUCCESS],
            ['order_status', '<>', OrderStatusEnum::CANCELLED]
        ];
        if (!is_null($startDate) && !is_null($endDate)) {
            $filter[] = ['pay_time', '>=', strtotime($startDate)];
            $filter[] = ['pay_time', '<', strtotime($endDate) + 86400];
        }
        return $this->getOrderTotal($filter);
    }

    /**
     * 获取未发货订单数量
     * @return int
     */
    public function getNotDeliveredOrderTotal(): int
    {
        $filter = [
            ['pay_status', '=', PayStatusEnum::SUCCESS],
            ['delivery_status', '=', DeliveryStatusEnum::NOT_DELIVERED],
            ['order_status', 'in', [OrderStatusEnum::NORMAL, OrderStatusEnum::APPLY_CANCEL]],
            ['order_parent_id', '>', 0]
        ];
        return $this->getOrderTotal($filter);
    }

    /**
     * 获取未付款订单数量
     * @return int
     */
    public function getNotPayOrderTotal(): int
    {
        $filter = [
            ['pay_status', '=', PayStatusEnum::PENDING],
            ['order_status', '=', OrderStatusEnum::NORMAL]
        ];
        return $this->getOrderTotal($filter);
    }

    /**
     * 获取订单总数
     * @param array $filter
     * @return int
     */
    private function getOrderTotal(array $filter = []): int
    {
        // 获取订单总数量
        return $this->where($filter)
            ->where('is_delete', '=', 0)
            ->count();
    }

    /**
     * 获取某天的总销售额
     * @param null $startDate
     * @param null $endDate
     * @return float
     */
    public function getOrderTotalPrice($startDate = null, $endDate = null): float
    {
        // 查询对象
        $query = $this->getNewQuery();
        // 设置查询条件
        if (!is_null($startDate) && !is_null($endDate)) {
            $query->where('pay_time', '>=', strtotime($startDate))
                ->where('pay_time', '<', strtotime($endDate) + 86400);
        }
        // 总销售额
        return $query->where('pay_status', '=', PayStatusEnum::SUCCESS)
            ->where('order_status', '<>', OrderStatusEnum::CANCELLED)
            ->where('is_delete', '=', 0)
            ->sum('pay_price');
    }

    /**
     * 获取某天的下单用户数
     * @param string $day
     * @return float|int
     */
    public function getPayOrderUserTotal(string $day)
    {
        $startTime = strtotime($day);
        return $this->field('user_id')
            ->where('pay_time', '>=', $startTime)
            ->where('pay_time', '<', $startTime + 86400)
            ->where('pay_status', '=', PayStatusEnum::SUCCESS)
            ->where('is_delete', '=', '0')
            ->group('user_id')
            ->count();
    }
}
